<template>
  <div class="">
    <commentEditor @submit="submit"></commentEditor>
    <div class="mt20">
      <commentList
        :list="commentInfo.list"
        :count="commentInfo.count"
        @clickMore="clickMore"
        @clickChildMore="clickChildMore"></commentList>
    </div>
  </div>
</template>

<script lang="ts" setup>
  import commentEditor from '@/components/comment/comment-editor.vue';
  import commentList from '@/components/comment/comment-list.vue';
  import { addComment, getCommentList, getCommentChildList } from '@/apis/article';
  import type { ICommentInfo, IComment, IPagination } from '@/apis/type';
  const props = defineProps(['blogId']);
  const listParams: IPagination = {
    blog_id: '',
    page: 1,
    pageSize: 10
  };
  watch(
    () => props.blogId,
    val => {
      listParams.blog_id = val;
      getList();
    }
  );
  // 评论信息
  const commentInfo = ref({} as ICommentInfo);
  const getList = async () => {
    const res = await getCommentList(listParams);
    if (res.code == 200) {
      if (commentInfo.value.list) {
        commentInfo.value.list = commentInfo.value.list.concat(res.data.list);
      } else {
        commentInfo.value.list = res.data.list;
      }
      commentInfo.value.count = res.data.count;
    }
  };
  // 点击查看 回复评论 更多
  const clickChildMore = async (param: IComment) => {
    const params: IPagination = {
      blog_id: param.blog_id,
      pid: param.id,
      page: param.childPage + 1,
      pageSize: 5
    };
    const res = await getCommentChildList(params);
    commentInfo.value.list.map((item: IComment) => {
      if (param.id == item.id) {
        ++item.childPage;
        if (item.children && item.children.length > (params.page - 1) * params.pageSize)
          item.children.length = (params.page - 1) * params.pageSize;
        item.children = (item.children || []).concat(res.data);
      }
    });
  };
  // 点击查看 评论 更多
  const clickMore = () => {
    listParams.page++;
    getList();
  };
  // 提交评论
  const submit = async (params: IComment) => {
    const obj = {
      ...params,
      blog_id: listParams.blog_id
    };
    const res = await addComment(obj);
    if (res.code == 200) {
      ElMessage.success(res.msg);
      commentInfo.value.list.unshift(obj);
      commentInfo.value.count++;
    }
  };
</script>

<style lang="scss" scoped></style>
